package cn.com.chec.en.controller.scheduler;

import java.text.ParseException;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.quartz.CronTrigger;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;

public class DumpMysqlDataScheduler {
	protected static final Logger logger = Logger
			.getLogger(DumpMysqDataJob.class);
	public static final String JOBNAME = "dumpMysqlData";

	public void startJob(String cronExpression, String tblNames,
			String destFileDir) {
		Scheduler sched = null;
		try {
			logger.info("[scheduler] #startJob# ------- Initializing ----------------------");
			sched = SchedulerConstants.schedulerFactory.getScheduler();

			logger.info("[scheduler] #startJob# ------- Scheduling Jobs -------------------");

			JobDetail job = new JobDetail("dumpMysqlData",
					"dumpMysqlDataGroupName", DumpMysqDataJob.class);
			JobDataMap jobDataMap = new JobDataMap();
			jobDataMap.put("tblNames", tblNames);
			jobDataMap.put("destFileDir", destFileDir);
			job.setJobDataMap(jobDataMap);

			CronTrigger trigger = new CronTrigger("dumpMysqlData",
					"dumpMysqlDataGroupName");
			trigger.setCronExpression(StringUtils.isBlank(cronExpression) ? "1 1 1 * * ?"
					: cronExpression);

			sched.scheduleJob(job, trigger);
			logger.info("[scheduler] #startJob# " + job.getFullName()
					+ " CronExpression " + trigger.getCronExpression());

			logger.info("[scheduler] #startJob# ------- Starting Scheduler ----------------");
			sched.start();
		} catch (SchedulerException e) {
			logger.error("[scheduler] #startJob#  scheduler is error ! ", e);
			try {
				if (!sched.isShutdown())
					sched.shutdown();
			} catch (SchedulerException e1) {
				logger.error(
						"[scheduler] #startJob#  scheduler stop errors ! ", e);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

	public void removeJob() {
		logger.info("[scheduler] #removeJob# start ******************");
		try {
			Scheduler sched = SchedulerConstants.schedulerFactory
					.getScheduler();
			if (sched == null) {
				logger.info("[scheduler] #removeJob#  Scheduler == null return ");
				return;
			}

			sched.pauseTrigger("dumpMysqlData", "dumpMysqlDataTriggerName");

			sched.unscheduleJob("dumpMysqlData", "dumpMysqlDataTriggerName");

			sched.deleteJob("dumpMysqlData", "dumpMysqlDataGroupName");

			logger.info("[scheduler] #removeJob# end ******************");
		} catch (SchedulerException e) {
			logger.info("[scheduler] #removeJob# error", e);
		}
	}

	public static void main(String[] args) {
		DumpMysqlDataScheduler scheduler = new DumpMysqlDataScheduler();
		scheduler
				.startJob("1 4 * * * ?", "tbl_news_i tbl_log_i", "c:/sqlDump/");
	}
}